python: 从pdf中提取图片

fitz库:提取pdf中的图片,超好用的!

针对python 3.10
利用fitz库读取文件:

import fitz
file = 'test.pdf'
doc = fitz.open(file)

获得doc的对象数:

lenXREF = doc.xref_length()

遍历每一个对象,并打印:

for i in range(1, nums):
	# 定义对象字符串
	text =  doc.xref_object(i);
	print(i, text)
	


import fitz
import time
import re
import os

#1.使用正则表达式查找PDF中的图片
def pdfTOpic(path,pic_path):#path:pdf的路径,pic_path:图片保存的路径
    t0 = time.perf_counter() #python 3.8已经不支持time.clock了
    #使用正则表达式来查找图片
    checkXO = r"/Type(?= */XObject)"
    checkIM = r"/Subtype(?= */Image)"
    #打开pdf
    doc = fitz.open(path)
    #图片计数
    imgCount = 0
    lenXREF = doc.xref_length()

    #打印pdf的信息
    print("文件名:{},页数:{},对象:{}".format(path,len(doc),lenXREF-1))

    #遍历每一个对象
    for i in range(1,lenXREF):
        #定义对象字符串
        text = doc.xref_object(i)
        isXObject = re.search(checkXO,text)
        #使用正则表达式查看是否是图片
        isImage = re.search(checkIM,text)
        #如果不是对象也不是图片,则continue
        if not isXObject or not isImage:
            continue
        imgCount+=1
        #根据索引生成图像
        pix = fitz.Pixmap(doc,i)
        #根据pdf的路径生成图片的名称
        new_name = path.replace('\\','_')+"_img{}.png".format(imgCount)
        new_name = new_name.replace(':','')

        #如果pix.n<5,可以直接存为png
        if pix.n<5:
            pix.writePNG(os.path.join(pic_path,new_name))
        #否则先转换CMYK
        else:
            pix0 = fitz.Pixmap(fitz.csRGB,pix)
            pix0.writePNG(os.path.join(pic_path,new_name))
            pix0 = None
        #释放资源
        pix = None
        t1 = time.perf_counter()
        print("运行时间:{}s".format(t1-t0))
        print("提取了{}张图片".format(imgCount))

if __name__ == '__main__':
    #pdf路径
    path = r'E:\PythonExperiment\Numerial.pdf'
    #创建保存图片的文件夹
    pic_path = r'E:\PythonExperiment\extractPictrue'
    if os.path.exists(pic_path):
        print("文件夹已存在,请重新创建文件夹!")
        raise SystemExit
    else:
        os.mkdir(pic_path)
    m=pdfTOpic(path,pic_path)
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值